#include "qdatafilter.h"
#include <QDir>
#include <QFile>
#include <QTextStream>
#include <QDebug>

QDataFilter::QDataFilter(QObject *parent) :
    QObject(parent)
{
}

QStringList QDataFilter::Filter(QString strFnSeekFrom, QString strSeekInfo)
{
    QStringList strResList;
    QString strRes("");

    QString strTrimmedSeekInfo = strSeekInfo;
    if (strTrimmedSeekInfo.endsWith("\n"))
    {
        strTrimmedSeekInfo.chop(1);
    }
    strTrimmedSeekInfo.trimmed();
    //qDebug() << strTrimmedSeekInfo;

    QFile seekFile(strFnSeekFrom);
    if(!seekFile.open(QFile::ReadOnly | QFile::Text))
    {
        qDebug() << "文件不存在!";
        return strResList;
    }
    while(!seekFile.atEnd())
    {
        QString strLine = seekFile.readLine();
        if (strLine.endsWith("\n"))
        {
            strLine.chop(1);
        }
        strLine = strLine.trimmed();

        QStringList strLineList = strLine.split(char(9));
        if(strLineList.count() < 2)
            continue;
        QString strName = strLineList.at(1);
        if (0 == QString::compare(strName, strTrimmedSeekInfo))
        //if(strLine.contains(strTrimmedSeekInfo))
        {
            strRes = strLine;
            strResList.append(strRes);
        }
    }
    return strResList;
}

void QDataFilter::Filter(QString strFnSeekFrom, QString strFnSeekInfo, QString strFnOutput)
{
    QFile outputFile(strFnOutput);
    if(!outputFile.open(QFile::WriteOnly | QFile::Text))
    {
        qDebug() << "无法写入查找结果!";
        return;
    }
    QTextStream out(&outputFile);

    QFile seekInfoFile(strFnSeekInfo);
    if(!seekInfoFile.open(QFile::ReadOnly | QFile::Text))
    {
        qDebug() << "信息文件不存在!";
        return;
    }

    QString strSeekInfo;
    while(!seekInfoFile.atEnd())
    {
        strSeekInfo = seekInfoFile.readLine();

        foreach(QString res, Filter(strFnSeekFrom, strSeekInfo))
        {
            if (!res.isEmpty())
            {
                out << res << endl;
            }
        }
    }
}
